/*
 * LifeTimeoutManager.cpp
 *
 *  Created on: 23/06/2014
 *      Author: Vitor
 */

#include "LifeTimeoutManager.h"

LifeTimeoutManager::LifeTimeoutManager() {
}

LifeTimeoutManager::~LifeTimeoutManager() {
}

void LifeTimeoutManager::run() {
	while (Globals::active.get()) {
		Globals::peers.lock();
		unsigned int current_time = SDL_GetTicks();
		unsigned int lostIpAddr;

		auto it = Globals::peers.get().begin();
		while (it != Globals::peers.get().end()) {
			if (current_time - it->second > TIMEOUT) {
				printf(
						"No de endereco %x timeout. Retirado do mapa de peers.\n",
						it->first);
				lostIpAddr = it->first;
				Globals::peers.get().erase(it++);

				if (Globals::peer.get().get_ip_address()
						== Balancer::get_manager_ip()) {
					Thread balancer([lostIpAddr] () {
						auto& balancer = Balancer::get_instance();
						balancer.run(Balancer::NODE_LOSS,lostIpAddr);
					});

					balancer.start();
				}
			} else {
				it++;
			}
		}

		Globals::peers.unlock();
		SDL_Delay(20);
	}
}
